package org.lzy.shop.good

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.textview.MaterialTextView
import com.google.gson.Gson

import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lzy.shop.Constant
import org.lzy.shop.Constant.GOODID
import org.lzy.shop.R
import org.lzy.shop.activity.CommentListActivity
import org.lzy.shop.activity.CustomMsgListActivity
import org.lzy.shop.activity.LoginActivity
import org.lzy.shop.activity.SubmitOrderActivity
import org.lzy.shop.adapter.CommentAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.cart.CartItem
import org.lzy.shop.cart.ShoppingCartManager
import org.lzy.shop.databinding.ActivityGoodsinfoBinding
import org.lzy.shop.databinding.LayoutSpecSearchChipItemBinding
import org.lzy.shop.response.GoodsSpecResponse
import org.lzy.shop.util.BannerManager
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.StringUtils
import org.lzy.shop.util.setUrl
import org.lzy.shop.util.setUrlRound
import org.lzy.shop.viewmodel.GoodInfoModel

/**
 * 商品详情信息
 */
class GoodInfoActivity: BaseMvvmActivity<ActivityGoodsinfoBinding, GoodInfoModel>({ ActivityGoodsinfoBinding.inflate(it) })  {
     var goodsID:Int = 0

    var goodsPic: String? = null

    var goodsMainPic: String? = null


    var commentAdapter: CommentAdapter? =null
    private val mGoodsSpec = mutableListOf<GoodsSpecResponse>()

    private var cartManager: ShoppingCartManager?=null

    private var bannerData: List<String>? = null

    private val bannerManager by lazy {
        BannerManager(
            viewPager2 = binding.bannerViewpager,
            indicatorsContainer = binding.bannerIndicator,
            lifecycleOwner = this,
            dataList = bannerData ?: emptyList(),
            autoScrollDelay = 3000,
            isInfiniteLoop = true
        ).apply {
            // 设置图片加载器
            setImageLoader {
                    imageView, url ->
                // 使用Coil加载圆角图片
                setUrlRound(url, 8f, imageView)
            }
        }
    }



    override fun initView() {
        if (intent.extras != null) {
            val bundle = intent.extras
            goodsID = bundle!!.getInt(Constant.GOODID)
            goodsPic = bundle.getString(Constant.GOODPIC)
        }

        commentAdapter= CommentAdapter()
        binding.recyclerview.apply {
            layoutManager =
                LinearLayoutManager(this@GoodInfoActivity, LinearLayoutManager.VERTICAL, false)
            adapter = commentAdapter
        }
        cartManager = ShoppingCartManager.getInstance(this)

    }

    override fun requestData() {
        mViewModel.getGoodInfo(goodsID.toString() + "")
    }

    //商品图片直接带到下个页面
    var choosedialogPic: String? = null
    //选中的规格名
    var choosedialogName: String? = null

    var sortNum: Int? = null


    var specId: Int? = null

    override fun initData() {
        //商品详情回调
        mViewModel.goodInfoData.observeWithLifecycle(this){goodsInfoResponse ->
            goodsInfoResponse?.let {
                val goodsInfo = goodsInfoResponse.goodsInfo
                binding.goodsInfoPrice.text = goodsInfo.price.toString()
                binding.goodsInfoTitle.text = goodsInfo.title
                binding.goodsInfoSubtitle.text = goodsInfo.subTitle
                goodsMainPic = goodsInfo.mainPic

                val pics = goodsInfo.pics
                if (pics.isNotEmpty()) {
                    setupBanner(pics)
                }
                val contentPics = goodsInfo.pics
                if (contentPics.isNotEmpty()) {
                    for (url in contentPics) {
                        val imageView = ImageView(this)
                        // 设置布局参数
                        val params = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            1200 // 固定高度，可根据需求调整
                        )
                        imageView.layoutParams = params

                        // 使用Coil加载图片
                        setUrl(url, imageView)
                        // 添加到容器
                        binding.goodContent.addView(imageView)
                    }
                }
                val comments = goodsInfoResponse.comment
                if (comments.isNotEmpty()) {
                    val  numberComment= StringBuilder()
                    numberComment.append(getResString(R.string.user_comment)).append("(").append(comments.size).append(")")
                    binding.commentNumber.text=numberComment.toString()
                    commentAdapter?.submitList(comments)
                    //有评论显示
                    binding.commentLayout.visibility= View.VISIBLE
                }else{
                    //无评论不要显示了
                    binding.commentLayout.visibility= View.GONE
                }
            }

        }
       //获取规格后弹底部对话框
        mViewModel.goodSpecData.observeWithLifecycle(this){specResponses ->
            dismissLoading()
            specResponses?.let {
                BottomDialog.show(object : OnBindView<BottomDialog?>(R.layout.dialog_bottomsepc) {
                    override fun onBind(dialog: BottomDialog?, view: View) {
                        //商品名
                        val goodsNames = view.findViewById<MaterialTextView>(R.id.goods_names)
                        //商品图片
                        val dialogImg = view.findViewById<ShapeableImageView>(R.id.pic_dialog_choose_shop_info_bottom)
                        //商品价格
                        val dialogPrice = view.findViewById<MaterialTextView>(R.id.price_dialog_choose_shop_info_bottom)
                        dialogPrice.text = binding.goodsInfoPrice.text.toString()
                        //商品库存数量
                        val dialogStock = view.findViewById<MaterialTextView>(R.id.stock_dialog_choose_shop_info_bottom)
                        //加减
                        val ivGoodsAdd = view.findViewById<ShapeableImageView>(R.id.layout_goods_iv_goods_add)
                        val ivGoodsMinus = view.findViewById<ShapeableImageView>(R.id.layout_goods_iv_goods_jian)
                        //商品数量
                        val tvGoodsNums = view.findViewById<MaterialTextView>(R.id.layout_goods_tv_goods_num)
                        //立即购买
                        val nowbuy = view.findViewById<MaterialTextView>(R.id.dialog_nowbuy_bottom)
                        //加入购物车
                        val addCart = view.findViewById<MaterialTextView>(R.id.dialog_addcart_bottom)
                        //规格显示列表
                        val specRv = view.findViewById<ChipGroup>(R.id.chip_group)

                        goodsNames.text = binding.goodsInfoTitle.text.toString()
                        //显示图片
                        setUrl(goodsPic, dialogImg)
                        //显示规格流式布局
                        mGoodsSpec.clear()
                        mGoodsSpec.addAll(specResponses)
                        for (index in 0 until specResponses.size) {
                            var  chipItem: Chip
                            //这里也要需要判断一下复用的情况
                            val childCount =specRv.childCount
                            if (index < childCount) {
                                chipItem =specRv.getChildAt(index) as Chip
                            } else {
                                chipItem = createChipItem(specRv)
                                specRv.addView(chipItem)
                            }
                            chipItem.text = specResponses[index].name
                        }
                        specRv.setOnCheckedChangeListener { group, checkedId ->
                            for (index in 0 until specRv.childCount) {
                                if (specRv.getChildAt(index)?.id == checkedId) {
                                    specId= specResponses[index].id
                                    dialogPrice.text = specResponses[index].price
                                    choosedialogName= specResponses[index].name
                                    dialogStock.text= specResponses[index].stock
                                    break
                                }
                            }
                        }

                        //点加号增加数量1，按减号变0再按没什么用了
                        ivGoodsAdd.setOnClickListener {
                            var num = StringUtils.toInt(tvGoodsNums.text.toString())
                            num += 1
                            tvGoodsNums.text = num.toString()
                        }
                        ivGoodsMinus.setOnClickListener {
                            var num2 = StringUtils.toInt(tvGoodsNums.text.toString())
                            if (num2 > 1) {
                                num2 -= 1
                            }
                            tvGoodsNums.text = num2.toString()
                        }
                        sortNum = tvGoodsNums.text.toString().toInt()

                        nowbuy.setOnClickListener(object : View.OnClickListener {
                            override fun onClick(view: View?) {
                                if (TextUtils.isEmpty(choosedialogName)) {
                                    showToast(getResString(R.string.please_choose_spec))
                                    return
                                }
                                choosedialogPic=goodsPic
                                val bundle = Bundle()
                                bundle.putString(Constant.GOODSTITLE, binding.goodsInfoTitle.text.toString())
                                bundle.putString(Constant.GOODPIC, choosedialogPic)
                                bundle.putInt(Constant.GOODID, goodsID)
                                bundle.putString(Constant.GOODSSPEC, choosedialogName)
                                bundle.putString(Constant.GOODSPRICE, dialogPrice.text.toString())
                                bundle.putString(Constant.GOODSNUM, tvGoodsNums.text.toString())
                                val gson = Gson()
                                val cartItem = CartItem(
                                    goodsId = goodsID,
                                    goodsName = binding.goodsInfoTitle.text.toString(),
                                    goodsMainPic = choosedialogPic ?: "",
                                    spec = listOf(GoodsSpecResponse().apply {
                                        this.id = specId ?: 0
                                        this.goodsId = goodsID
                                        this.name = choosedialogName
                                        this.price = dialogPrice.text.toString()
                                        this.stock = dialogStock.text.toString()
                                    }),
                                    quantity = tvGoodsNums.text.toString().toInt(),
                                )

                                // 创建一个包含单个CartItem的列表并序列化为JSON
                                val cartItemList = listOf(cartItem)
                                val selectedItemsJson = gson.toJson(cartItemList)
                                bundle.putString(Constant.SELECTED_CART_ITEMS, selectedItemsJson)

                                startActivity(SubmitOrderActivity::class.java, bundle)
                            }
                        })
                        addCart.setOnClickListener {
                            if (TextUtils.isEmpty(choosedialogName)) {
                                showToast(getResString(R.string.please_choose_spec))
                            }else{
                                val goodsInfo = CartItem(
                                    goodsId = goodsID,
                                    goodsName = binding.goodsInfoTitle.text.toString(),
                                    goodsMainPic = goodsPic ?: "",
                                    spec = listOf(GoodsSpecResponse().apply {
                                        this.id = specId ?: 0
                                        this.goodsId = goodsID
                                        this.name = choosedialogName
                                        this.price=dialogPrice.text.toString()
                                    })
                                )
                                lifecycleScope.launch {
                                    val success = cartManager?.addToCart(goodsInfo, 1)
                                    withContext(Dispatchers.Main) {
                                        if (success == true) {
                                            // 显示加入购物车成功提示
                                            showToast("加入购物车成功")
                                        } else {
                                            showToast("加入购物车失败")
                                        }
                                    }
                                }
                            }

                        }
                    }
                })
            }
        }

    }

    private fun setupBanner(bannerList: List<String>) {
        // 保存数据
        this.bannerData = bannerList
        // 设置数据并初始化轮播图
        bannerManager.setData(bannerList)
        bannerManager.initialize()
    }

    private fun createChipItem(specRv: ChipGroup): Chip {
        val chipItem: Chip = LayoutSpecSearchChipItemBinding.inflate(LayoutInflater.from(this), specRv, false).root
        //刚创建的时候是没有选中的
        chipItem.isChecked=false
        chipItem.isCheckable=true
        chipItem.setOnCheckedChangeListener { p0, p1 ->
            if (p1) {
                chipItem.setTextColor(Color.WHITE)
                chipItem.setChipBackgroundColorResource(R.color.colorPrimary)
            }else{
                chipItem.setTextColor(Color.BLACK)
                chipItem.setChipBackgroundColorResource(R.color.Surface)
            }
        }
        chipItem.id= specRv.childCount
        return chipItem
    }

    override fun allClick() {
        //加入购物车
        binding.actGoodsDetailsTvAddToCart.setOnClickListener {
            // 统一使用navigateWithTokenCheck方法
            if (isTokenValid()) {
                showBottomDialog()
            } else {
                startActivity(LoginActivity::class.java)
            }
        }

        //立即购买
        binding.actGoodsDetailsTvNowbuy.setOnClickListener {
            // 统一使用navigateWithTokenCheck方法
            if (isTokenValid()) {
                showBottomDialog()
            } else {
                startActivity(LoginActivity::class.java)
            }
        }

        //客服聊天
        binding.actGoodsDetailsLlChat.setOnClickListener {
            // 使用navigateWithTokenCheck简化代码
            navigateWithTokenCheck(CustomMsgListActivity::class.java)
        }

        //评论查看全部
        binding.commentMore.setOnClickListener {
            // 使用navigateWithTokenCheck简化代码，并传递参数
            val bundle = Bundle()
            bundle.putString(GOODID, goodsID.toString())
            navigateWithTokenCheck(CommentListActivity::class.java, bundle)
        }
    }

    //判断Token是否有效
    private fun isTokenValid(): Boolean {
        val token = DataStoreUtils.getToken(Constant.TOKEN)
        return !TextUtils.isEmpty(token)
    }

    private fun navigateWithTokenCheck(targetClass: Class<*>, bundle: Bundle? = null) {
        if (isTokenValid()) {
            if (bundle != null) {
                startActivity(targetClass, bundle)
            } else {
                startActivity(targetClass)
            }
        } else {
            startActivity(LoginActivity::class.java)
        }
    }

    private fun showBottomDialog() {
        showLoading()
        mViewModel.getGoodsSpec(goodsID)

    }


}